﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using eFatura.Properties;
using eFatura.Utility;
using eFatura.Utility.Grid;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace eFatura
{
    public partial class GidenFatura : XForm
    {
        string FaturaDurum;
        List<int> ModifiedRows = new List<int>();
        Fatura fatura = new Fatura();

        public GidenFatura(string faturaDurum)
        {
            InitializeComponent();
            FaturaDurum = faturaDurum;
        }

        private void Faturalar_Load(object sender, EventArgs e)
        {
            ShowOnlyBar();

            this.Text = "Giden Fatura (" + FaturaDurum + ")";
            dtBitis.EditValue = DateTime.Now;
            dtBaslangic.EditValue = DateTime.Now.AddMonths(-1);

            DataTable dt = AppSession.DataManager.ExecuteDataTable(Schema + "GetNebimEFatura", SirketId, dtBaslangic.EditValue, dtBitis.EditValue);

            gvFatura.Init(dt);
            RefreshFilter(dt);

            gvFatura.FormatAsDate("FisTarihi", "ValorTarihi");
            gvFatura.FormatAsNumber(2, "MalBedeli", "IskontoTutari", "KDVOrani", "KDVMatrahi", "KDV", "KDVOran2", "KDVMatrahi2", "KDV2", "KDVOrani3", "KDVMatrahi3", "KDV3", "OTVOrani", "OTVMatrahi", "OTV", "TevkifatKdvOrani", "TevkifatKdvMatrahi", "TevkifatKdv", "ToplamMiktar");
            gvFatura.FormatAsNumber(3, "NetTutar");
            gvFatura.AddSummary("MalBedeli", "IskontoTutari", "KDVMatrahi", "KDV", "OTVMatrahi", "OTV", "TevkifatKdvMatrahi", "TevkifatKdv", "ToplamMiktar", "NetTutar");
            gvFatura.SetCaptions("StokFisiNo:Stok Fişi No", "FisTarihi:Fiş Tarihi", "Tamamlandi:Tamamlandı", "GonderimTarihi:Gönderim Tarihi", "FisTipi:Fiş Tipi", "FisNo:Fiş No", "KDVOrani:KDV-1 Oranı", "KDVMatrahi:KDV-1 Matrahı", "KDV:KDV-1", "KDVOran2:KDV-2 Oranı", "KDVMatrahi2:KDV-2 Matrahı", "KDV2:KDV-2", "KDVOrani3:KDV-3 Oranı", "KDVMatrahi3:KDV-3 Matrahı", "KDV3:KDV-3", "FisTamamlandiMi:Fiş Tamamlandı", "KayitTarihi:Kayıt Tarihi");
            gvFatura.MakeColumnInvisible("URL", "PayFlexId", "nFirmax");

            if (isYonetici)
            {
                GridManager gm = GridManager.GetManager(gvFatura);
                gm.GridMenu.AddMenu("Gönder", SendEFatura, Resources.up_16x16);
                gm.GridMenu.AddMenu("Durum Güncelle", DurumKontrol, Resources.recurrence_16x16);
                if (WhoAmI == 1 || WhoAmI == 2)
                    gm.GridMenu.AddMenu("Mükellef Sorgula", MukellefSorgula, Resources.up_16x16);
            }


            gvFatura.RowCellClick += gvFatura_RowCellClick;
            gvFatura.MakeReadOnly("Iade");

            gvFatura.BestFitColumns();
            gvFatura.Columns["ZarfDurum"].Width = 150;

            gvFatura.SetAlternateRowStyle(false);

            gvFatura.MouseMove += gvFatura_MouseMove;
            gvFatura.RowCellStyle += gvFatura_RowCellStyle;

            gvFatura.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
            LoadLayout();
        }

        private void MukellefSorgula(object sender, EventArgs e)
        {
            fatura.eFaturaMukellefGuncelle(true, SirketId);
        }

        private void gvFatura_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1 && e.Column.FieldName == "eFaturaNo")
            {
                if (e.CellValue.ToStringNN() != "")
                {
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Underline);
                    e.Appearance.ForeColor = Color.Navy;
                }
            }

        }

        private void gvFatura_MouseMove(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo info = view.CalcHitInfo(new Point(e.X, e.Y));

            if (info.InRowCell && info.Column.FieldName == "eFaturaNo" && info.RowHandle > -1)
            {
                string faturaNo = view.GetRowCellValue(info.RowHandle, "eFaturaNo").ToStringNN();
                if (faturaNo != "")
                    view.GridControl.Cursor = Cursors.Hand;
                else
                    view.GridControl.Cursor = Cursors.Default;
            }
            else
                view.GridControl.Cursor = Cursors.Default;

        }

        private void RefreshFilter(DataTable dt)
        {
            if (FaturaDurum == "Tümü")
            {
                gvFatura.ActiveFilterString = "";
            }
            else
            {
                string filters = "[FaturaDurum] =  '" + FaturaDurum + "' OR [StokFisiNo] In (";

                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["FaturaDurum"].ToStringNN() == FaturaDurum)
                        filters += "'" + dr["StokFisiNo"].ToStringNN() + "',";
                }

                filters = filters.RemoveIfEndsWith(",") + ")";

                gvFatura.ActiveFilterString = filters;
            }
        }

        private void gvFatura_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            if (e.Column.FieldName == "eFaturaNo")
            {
                string url = gvFatura.GetFocusedRowCellValue("URL").ToString();
                if (url != "")
                {
                    FaturaViewer viewer = new FaturaViewer(url);
                    viewer.ShowDialog();
                }
            }
        }

        private void DurumKontrol(object sender, EventArgs e)
        {
            ModifiedRows.Add(gvFatura.FocusedRowHandle);

            long PayFlexId = (long)gvFatura.GetFocusedRowCellValue("PayFlexId");
            fatura.DurumGuncelle(PayFlexId);
            VeriyiGuncelle();
        }

        private void SendEFatura(object sender, EventArgs e)
        {
            ModifiedRows.Add(gvFatura.FocusedRowHandle);

            int nStokFisiId = gvFatura.GetFocusedRowCellValue("StokFisiNo").ToIntNN();
            int iade = gvFatura.GetFocusedRowCellValue("Iade").ToIntZero();

            try
            {
                fatura.Gonder(nStokFisiId, iade);
                VeriyiGuncelle();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Hata");
            }
        }

        private DataTable VeriyiGuncelle()
        {

            //Fatura f = new Fatura();
            //f.eFaturaCariGuncelle();

            decimal stokFisi = gvFatura.GetFocusedRowCellValue("StokFisiNo").ToDecimalNN();
            DataTable dt = AppSession.DataManager.ExecuteDataTable(Schema + "GetNebimEFatura", SirketId, dtBaslangic.EditValue, dtBitis.EditValue);
            gvFatura.VeriyiGuncelle(dt);
            gvFatura.BestFitColumns();
            gvFatura.Columns["ZarfDurum"].Width = 150;
            gvFatura.FocusedRowHandle = gvFatura.LocateByValue(0, gvFatura.Columns["StokFisiNo"], stokFisi);
            return dt;
        }

        private void gvFatura_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if (ModifiedRows.Contains(e.RowHandle))
                    e.Appearance.BackColor = Color.LightGoldenrodYellow;
        }

        private void btnYenile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DataTable dt = VeriyiGuncelle();

            ModifiedRows.Clear();
            RefreshFilter(dt);

            AppSession.MainForm.InitDagilim();
        }

        private void btnDuzeniKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            List<string> pairs = new List<string>();
            for (int i = 0; i < gvFatura.VisibleColumns.Count; i++)
            {
                GridColumn col = gvFatura.VisibleColumns[i];
                string pair = col.FieldName + ":" + i.ToString() + ":" + col.Width;
                pairs.Add(pair);
            }
            string result = String.Join(",", pairs);

            AppSession.Ayar.GidenFatura = result;
            AppSession.Ayar.Save();
            XtraMessageBox.Show("Sütunların sırası, görünürlüğü ve genişliği kaydedildi. Form, artık sizin için bu şekilde açılacak.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        public void LoadLayout()
        {
            this.Cursor = Cursors.WaitCursor;

            if (AppSession.Ayar.GidenFatura != "")
            {
                foreach (GridColumn gc in gvFatura.Columns)
                    gc.Visible = false;

                foreach (string pair in AppSession.Ayar.GidenFatura.Split(",".ToCharArray()))
                {
                    try
                    {
                        string[] vals = pair.Split(":".ToCharArray());
                        string colName = vals[0];
                        int index = vals[1].ToIntNN();
                        int width = vals[2].ToIntNN();
                        gvFatura.Columns[colName].VisibleIndex = index;
                        gvFatura.Columns[colName].Width = width;
                    }
                    catch
                    {
                        XtraMessageBox.Show("Sütun değişiklikleri olduğu için sütunları yeniden düzenlemelisiniz.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        foreach (GridColumn gc in gvFatura.Columns)
                            gc.Visible = true;

                        AppSession.Ayar.GidenFatura = "";
                        AppSession.Ayar.Save();
                        this.Cursor = Cursors.Default;
                        return;
                    }
                }
            }
            this.Cursor = Cursors.Default;
        }
    }
}